<?php

namespace App\Jobs\Posts;

use App\Models\Posts\WxPost;
use App\Models\Posts\WxPostsVote;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class UpdatePostOnlyTextJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $post_id = 0;
    public $tries = 1;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($post_id)
    {
        //
        $this->post_id = $post_id;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        if(_empty_($this->post_id)){
            $post_ids = WxPost::whereNull('is_only_text')->orderBy('id', 'desc')->limit(50)->pluck('id')->toArray();
            if($post_ids){
                $is_noly_posts = [];
                $not_noly_Posts = [];
                foreach ($post_ids as $post_id){
                    $post = WxPost::find($post_id);
                    if(mb_strlen($post->posts_content) == mb_strlen(strip_tags($post->posts_content))){
                        $is_noly_posts[] = $post_id;
                    }else{
                        $not_noly_Posts[] = $post_id;
                    }
                }
                if(!_empty_($is_noly_posts)){
                    WxPost::withoutSyncingToSearch(function () use ($is_noly_posts){
                        WxPost::whereIn('id', $is_noly_posts )->update(['is_only_text'=>1]);
                    });
                }
                if(!_empty_($not_noly_Posts)){
                    WxPost::withoutSyncingToSearch(function () use ($not_noly_Posts){
                        WxPost::whereIn('id', $not_noly_Posts )->update(['is_only_text'=>0]);
                    });
                }
            }
        }else{
            $post = WxPost::find($this->post_id);
            if($post){
                if(mb_strlen($post->posts_content) == mb_strlen(strip_tags($post->posts_content))){
                    WxPost::withoutSyncingToSearch(function (){
                        WxPost::where('id', $this->post_id )->update(['is_only_text'=>1]);
                    });
                }else{
                    WxPost::withoutSyncingToSearch(function (){
                        WxPost::where('id', $this->post_id )->update(['is_only_text'=>0]);
                    });
                }
            }
        }
    }
}
